<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2024/5/10
 * Time: 16:01
 */

namespace app\zyhsapi\controller\v5;

use app\common\lib\Util;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\ZyhsInteractiveMessage;
use think\response\Json;

class InteractiveMessage extends ZyhsAuth
{
    /**
     * 列表
     * @return mixed
     * @throws \Exception
     */
    public function index()
    {
        $zyhsInteractiveMessageModel = new ZyhsInteractiveMessage();
        $data = $zyhsInteractiveMessageModel->getListPage($this->user['id'], 'id', [], 1);
        $data['data'] = $zyhsInteractiveMessageModel->dataInit($data['data']);
        $res = [];
        foreach ($data['data'] as $datum)
        {
            $typeInfo = $zyhsInteractiveMessageModel->getTypeInfo($datum);
            $res[] = [
                'name' => $typeInfo['nickname'],
                'avatar' => $typeInfo['avatar'],
                'tip' => $typeInfo['tip'],
                'content' => $typeInfo['content'],
                'content_tip' => $typeInfo['content_tip'],
                'target' => $typeInfo['target'],
                'link' => $typeInfo['link'],
                'astr_id' => $typeInfo['astr_id'],
                'owner_tag' => $typeInfo['owner_tag'],
                'time_des' => Util::timeToStr($datum['create_time']),
                'read_status' => $datum['read_time'] > 0 ? 1 : 0,
                'id' => $datum['id'],
            ];
        }
        $data['data'] = $res;
        return show(config('code.success'), 'success', $data);
    }

    /**
     * 消息已读
     * @return Json
     * @throws \Exception
     */
    public function readMsg()
    {
        $id = input('id/d', 0);
        if ($id)
        {
            $data = (new ZyhsInteractiveMessage())->getInfoById($id, ['uid', 'read_time']);
            if (!$data || $data['uid'] !== $this->user['id'] || $data['read_time'])
            {
                return show(config('code.success'), 'success.');
            }
            $ids = [$id];
        } else
        {
            $ids = (new ZyhsInteractiveMessage())->unreadMsgIds(1, $this->user['id']);
        }
        (new ZyhsInteractiveMessage())->updateData(1, $this->user['id'], $ids, ['read_time' => $this->request->time()]);
        return show(config('code.success'), 'success.');
    }

    /**
     * 删除消息
     * @return Json
     * @throws \Exception
     */
    public function delMsg()
    {
        $id = input('id/d', 0);
        $data = (new ZyhsInteractiveMessage())->getInfoById($id, ['uid', 'delete_time']);
        if (!$data || $data['uid'] !== $this->user['id'] || $data['delete_time'])
        {
            return show(config('code.success'), 'success.');
        }
        (new ZyhsInteractiveMessage())->updateData(1, $this->user['id'], [$id], ['delete_time' => $this->request->time(), 'read_time' => $this->request->time()]);
        return show(config('code.success'), 'success.');
    }
}
